/**
 * 直方图的计算和显示
 **/

#include <opencv2/opencv.hpp>
#include <iostream>

using namespace std;

int main(int argc, char** argv) {
    if (argc!=2) {
        cout << "Compute Color Histogram\nUsage: " << argv[0] << " <imagename>" << endl;
        return -1;
    }

    cv::Mat src = cv::imread(argv[1], 1);
    if (src.empty()) {
        cout << "Cannnot load " << argv[1] << endl; return -1;
    }

    cv::Mat hsv;
    cv::cvtColor(src, hsv, cv::COLOR_BGR2HSV);

    float h_ranges[] = {0, 180};    // 色相范围 0-180
    float s_ranges[] = {0, 255};
    const float* ranges[] = {h_ranges, s_ranges};
    int histSize[] = {30, 32}, ch[] = {0, 1};

    cv::Mat hist;
    cv::calcHist(&hsv, 1, ch, cv::noArray(), hist, 2, histSize, ranges);
    cv::normalize(hist, hist, 0, 255, cv::NORM_MINMAX);

    int scale = 10;
    cv::Mat hist_image(histSize[0]*scale, histSize[1]*scale, CV_8UC3);

    // draw hist
    for (int h = 0; h < histSize[0]; h++) {
        for(int s = 0; s < histSize[1]; s++){
            float h_val = hist.at<float>(h,s);
            cv::rectangle(hist_image, cv::Rect(h*scale, s*scale, scale, scale),cv::Scalar::all(h_val), -1);
        }
    }

    cv::imshow("image", src);
    cv::imshow("H-S Histogram", hist_image);
    cv::waitKey(0);
    
    return 0;
}
